package com.slm.krstartimes.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.slm.krstartimes.R;
import com.slm.krstartimes.activity.MainActivity;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.Rotate3d;
import com.slm.krstartimes.utils.SlideViewSAX;
import com.slm.krstartimes.utils.StreamRequest;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by dllo on 15/7/30.
 * 最新
 */
public class MainMenuFragment extends android.support.v4.app.Fragment implements View.OnClickListener {
    private static final int IMAGE1 = R.mipmap.recommend_news;
    private static final int IMAGE2 = R.mipmap.topphone2;
    private static final int IMAGE3 = R.mipmap.androidhome3;
    private static final int IMAGE4 = R.mipmap.ios_new2;
    private static final int IMAGE5 = R.mipmap.wphome3;
    private static final int IMAGE6 = R.mipmap.digital;
    private static final int IMAGE7 = R.mipmap.window10;
    private ViewGroup vp_recommend, vp_tophone, vp_android, vp_ios, vp_wp, vp_degitl, vp_windows;
    private List<HashMap<String, String>> maps;//存放 imageUrl的HashMap的List
    private LinearLayout main_recommended_page;
    private LinearLayout main_topphone;
    private LinearLayout main_android_home;
    private LinearLayout main_ios_home;
    private LinearLayout main_wp_home;
    private LinearLayout main_degital;
    private LinearLayout main_Windows;
    private ViewPager viewPager;
    private Handler handler, handler1;
    private ImageView img_recommend, img_android, img_ios, img_topphnoe, img_wp, img_window, img_degital;
    private boolean which = false;//which用于区别当前图片的状态
    private List<String> imgUrl;
    private int count = 0;

    /*产生2-5随机整数*/
    public static int rand() {
        int rand = (int) (2 + Math.random() * (5 - 2 + 1));
        return rand;
    }

    /*产生0-1随机整数*/
    public static int minRand() {
        int rand = (int) (0 + Math.random() * (1 - 0 + 1));
        return rand;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.main_menu_listview, null);

        initView(view);

        getData("slide", img_recommend);
        getData("android", img_android);
        getData("ios", img_ios);
        getData("wp", img_wp);
        getData("windows", img_window);

        overturn();


        return view;
    }

    /**
     * 图片翻转动画
     */
    private void overturn() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if (message.what == 201) {
                    if (!which) {
                        applyRotation(0, 0, -90, vp_recommend, img_recommend, 0);//左旋90度
                    } else {
                        applyRotation(0, 0, 90, vp_recommend, img_recommend, IMAGE1);//右旋90度
                    }
                } else if (message.what == 202) {
                    if (!which) {
                        applyRotation(0, 0, 90, vp_tophone, img_topphnoe, 4);//右旋90度
                    } else {
                        applyRotation(0, 0, -90, vp_tophone, img_topphnoe, IMAGE2);//左旋90度
                    }
                } else if (message.what == 203) {
                    if (!which) {
                        applyRotation(0, 0, 90, vp_android, img_android, 1);//右旋90度
                    } else {
                        applyRotation(0, 0, -90, vp_android, img_android, IMAGE3);//左旋90度
                    }
                } else if (message.what == 204) {
                    if (!which) {
                        applyRotation(0, 0, -90, vp_ios, img_ios, 2);//右旋90度
                    } else {
                        applyRotation(0, 0, 90, vp_ios, img_ios, IMAGE4);//左旋90度
                    }
                } else if (message.what == 205) {
                    if (!which) {
                        applyRotation(0, 0, -90, vp_wp, img_wp, 3);//右旋90度
                    } else {
                        applyRotation(0, 0, 90, vp_wp, img_wp, IMAGE5);//左旋90度
                    }
                } else if (message.what == 206) {
                    if (!which) {
                        applyRotation(0, 0, -90, vp_degitl, img_degital, 0);//右旋90度
                    } else {
                        applyRotation(0, 0, 90, vp_degitl, img_degital, IMAGE6);//左旋90度
                    }
                } else if (message.what == 207) {
                    if (!which) {
                        applyRotation(0, 0, -90, vp_windows, img_window, 4);//右旋90度
                    } else {
                        applyRotation(0, 0, 90, vp_windows, img_window, IMAGE7);//左旋90度
                    }
                }

                return false;
            }
        });
    }

    /**
     * 初始化
     *
     * @param view
     */
    private void initView(View view) {
        maps = new ArrayList<>();
        viewPager = (ViewPager) getActivity().findViewById(R.id.mainviewPager);
        main_recommended_page = (LinearLayout) view.findViewById(R.id.main_recommended_page);
        main_topphone = (LinearLayout) view.findViewById(R.id.main_topphone);
        main_android_home = (LinearLayout) view.findViewById(R.id.main_android_home);
        main_ios_home = (LinearLayout) view.findViewById(R.id.main_ios_home);
        main_wp_home = (LinearLayout) view.findViewById(R.id.main_wp_home);
        main_degital = (LinearLayout) view.findViewById(R.id.main_degital);
        main_Windows = (LinearLayout) view.findViewById(R.id.main_Windows);
        main_recommended_page.setOnClickListener(this);
        main_topphone.setOnClickListener(this);
        main_android_home.setOnClickListener(this);
        main_ios_home.setOnClickListener(this);
        main_wp_home.setOnClickListener(this);
        main_degital.setOnClickListener(this);
        main_Windows.setOnClickListener(this);

        img_recommend = (ImageView) view.findViewById(R.id.IVmain_recommended_page);
        img_android = (ImageView) view.findViewById(R.id.IVmain_android_home);
        img_degital = (ImageView) view.findViewById(R.id.IVmain_degital);
        img_ios = (ImageView) view.findViewById(R.id.IVmain_ios_home);
        img_topphnoe = (ImageView) view.findViewById(R.id.IVmain_topphone);
        img_window = (ImageView) view.findViewById(R.id.IVmain_Windows);
        img_wp = (ImageView) view.findViewById(R.id.IVmain_wp_home);


        vp_recommend = (ViewGroup) view.findViewById(R.id.framlayout_recommend);
        vp_android = (ViewGroup) view.findViewById(R.id.framlayout_android);
        vp_degitl = (ViewGroup) view.findViewById(R.id.framlayout_degital);
        vp_ios = (ViewGroup) view.findViewById(R.id.framlayout_ios);
        vp_tophone = (ViewGroup) view.findViewById(R.id.framlayout_top);
        vp_windows = (ViewGroup) view.findViewById(R.id.framlayout_windows);
        vp_wp = (ViewGroup) view.findViewById(R.id.framlayout_WP);

        imgUrl = new ArrayList<>();
    }

    /**
     * 组件监听
     *
     * @param v
     */
    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.main_recommended_page:
                viewPager.setCurrentItem(1);
                break;
            case R.id.main_topphone:
                viewPager.setCurrentItem(2);
                break;
            case R.id.main_android_home:
                viewPager.setCurrentItem(3);
                break;
            case R.id.main_ios_home:
                viewPager.setCurrentItem(4);
                break;
            case R.id.main_wp_home:
                viewPager.setCurrentItem(5);
                break;
            case R.id.main_degital:
                viewPager.setCurrentItem(6);
                break;
            case R.id.main_Windows:
                viewPager.setCurrentItem(7);
                break;
        }
    }

    /**
     * 动画效果
     *
     * @param position
     * @param start
     * @param end
     * @param vg
     * @param imageView
     * @param IMAGE
     */
    private void applyRotation(int position, float start, float end, ViewGroup vg, ImageView imageView, int IMAGE) {
        // Find the center of the container
        //获取FrameLayout的x、y值。这样图片在翻转的时候会以这个x、y值为中心翻转。
        //这就是为什么我要用FrameLayout的原因。如果直接使用的是父容器RelativeLayout将会以RelativeLayout的中心为轴心
        //翻转。由于我的图片不是处于RelativeLayout的中心，翻转时就会有差错.效果可以看看下面的图片。
        //当然，有时候你就想要那样的效果。你也可以在自行调整centerX和centerY的值来达到你想要的效果
        final float centerX = vg.getWidth() / 2.0f;
        final float centerY = vg.getHeight() / 2.0f;
        final Rotate3d rotation =
                new Rotate3d(start, end, centerX, centerY, 310.0f, true);
        rotation.setDuration(1000);  //可设置翻转的时间，以ms为单位
        rotation.setFillAfter(true);
        rotation.setInterpolator(new AccelerateInterpolator());
        rotation.setAnimationListener(new DisplayNextView(imageView, IMAGE, vg));
        vg.startAnimation(rotation);  //开始翻转前90度
    }

    /**
     * 开启子线程自动翻转
     *
     * @param what
     */
    public void roll(final int what) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 0xABCL; i++) {
                    handler.sendEmptyMessage(what);
                    try {
                        Thread.sleep(2 * rand() * 1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
    }

    /**
     * 获取数据
     *
     * @param type
     * @param imageView
     */
    protected void getData(final String type, final ImageView imageView) {
        final Map<String, String> map = new HashMap<String, String>();

        StreamRequest request = new StreamRequest("http://api.ithome.com/xml/slide/" + type + ".xml",
                new Response.Listener<InputStream>() {
                    @Override
                    public void onResponse(InputStream inputStream) {
                        handler1 = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message message) {
                                if (message.what == 200) {
                                    final List<News> list = (List<News>) message.obj;

                                    imgUrl.add(list.get(minRand()).getImage());
                                    map.put(type, list.get(minRand()).getImage());
                                    maps.add((HashMap<String, String>) map);
                                    count++;
                                    if (count == 5) {
                                        for (int i = 201; i <= 207; i++) {
                                            roll(i);
                                        }
                                    }
                                }
                                return false;
                            }
                        });
                        SAXParserFactory spx = SAXParserFactory.newInstance();
                        try {
                            SAXParser sp = spx.newSAXParser();
                            sp.parse(inputStream, new SlideViewSAX(handler1));

                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Toast.makeText(getActivity(), "加载图片失败", Toast.LENGTH_SHORT).show();
            }
        });
        MainActivity.requestQueue.add(request);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    private final class DisplayNextView implements Animation.AnimationListener {
        private ImageView imageView;
        private int IMAGE;
        private ViewGroup vg;

        public DisplayNextView(ImageView imageView, int IMAGE, ViewGroup vg) {
            this.IMAGE = IMAGE;
            this.vg = vg;
            this.imageView = imageView;
        }

        public void onAnimationStart(Animation animation) {
        }

        public void onAnimationEnd(Animation animation) {
            //前90度翻转完成后，根据图片的状态翻转剩下的90度

            String s = new String();
            switch (IMAGE) {
                case 0:
                    for (int i = 0; i < maps.size(); i++) {
                        Set key = maps.get(i).keySet();
                        Iterator it = key.iterator();
                        while (it.hasNext()) {
                            if ("slide".equals(it.next().toString())) {
                                s = maps.get(i).get("slide");
                            }
                        }
                    }
                    break;
                case 1:
                    for (int i = 0; i < maps.size(); i++) {
                        Set key = maps.get(i).keySet();
                        Iterator it = key.iterator();
                        while (it.hasNext()) {
                            if ("android".equals(it.next().toString())) {
                                s = maps.get(i).get("android");
                            }
                        }
                    }
                    break;
                case 2:
                    for (int i = 0; i < maps.size(); i++) {
                        Set key = maps.get(i).keySet();
                        Iterator it = key.iterator();
                        while (it.hasNext()) {
                            if ("ios".equals(it.next().toString())) {
                                s = maps.get(i).get("ios");
                            }
                        }
                    }
                    break;
                case 3:
                    for (int i = 0; i < maps.size(); i++) {
                        Set key = maps.get(i).keySet();
                        Iterator it = key.iterator();
                        while (it.hasNext()) {
                            if ("wp".equals(it.next().toString())) {
                                s = maps.get(i).get("wp");
                            }
                        }
                    }
                    break;
                case 4:
                    for (int i = 0; i < maps.size(); i++) {
                        Set key = maps.get(i).keySet();
                        Iterator it = key.iterator();
                        while (it.hasNext()) {
                            if ("windows".equals(it.next().toString())) {
                                s = maps.get(i).get("windows");
                            }
                        }
                    }
                    break;
            }

            if (!which) {
                ImageLoader.ImageListener imageListener = ImageLoader.getImageListener(imageView,
                        R.mipmap.load, R.mipmap.load);// 参数说明:图片地址,默认图片,加载失败显示的图片
                MainActivity.imageLoader.get(s, imageListener);//加载图片
                vg.post(new SwapViews(0, vg));

            } else {
                imageView.setImageResource(IMAGE);
                vg.post(new SwapViews(1, vg));
            }
        }

        public void onAnimationRepeat(Animation animation) {
        }
    }

    private final class SwapViews implements Runnable {
        private final int mdirection;
        private ViewGroup vg;


        //我把API的例子改了，这里用一个方向变量来指明剩下的90度应该怎么翻转。
        public SwapViews(int direction, ViewGroup vg) {
            mdirection = direction;
            this.vg = vg;
        }

        public void run() {
            final float centerX = vg.getWidth() / 2.0f;
            final float centerY = vg.getHeight() / 2.0f;
            Rotate3d rotation;
            if (mdirection == 0) {
                rotation = new Rotate3d(90, 0, centerX, centerY, 310.0f, false);
                which = true;//待翻转完成后，修改图片状态
            } else {
                rotation = new Rotate3d(-90, 0, centerX, centerY, 310.0f, false);
                which = false;
            }
            rotation.setDuration(1000);
            rotation.setFillAfter(true);
            rotation.setInterpolator(new DecelerateInterpolator());
            vg.startAnimation(rotation);  //开始翻转余下的90度
        }
    }
}
